package com.nuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Chat implements Runnable {
	private Socket socket = null;

	public Chat(Socket client) {
		this.socket = client;
	}

	@Override
	public void run() {
		InputStream inputStream = null;
		OutputStream outputStream = null;

		try {
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			boolean chatting = true;
			// 设置缓存，发送的数据长度不能超过512字节
			byte[] buffer = new byte[512];
			while (chatting) {
				// 等待并接受客户端发送的数据，有阻塞作用
				int len = inputStream.read(buffer);
				String words = new String(buffer, 0, len).trim();
				System.out.println(words);
				// 鹦鹉学舌，发送并返回原话
				outputStream.write(("parrot:" + words).getBytes());
				if ("quit".equalsIgnoreCase(words)) {
					chatting = false;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

}
